﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;

namespace Arbalest.Web.Controllers
{
    public class HomeController : Controller
    {
 
        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        #region no-text coverage stuff
        // Stuff here are to be place here for test of concept.
        // To be placed else where
        
        private const string TempPath = @"C:\Temp";

        public ActionResult UploadFiles()
        {
            return View();
        }

        [HttpPost]
        public ActionResult UploadFiles(IEnumerable<HttpPostedFileBase> files)
        {
            
            //foreach (string upload in Request.Files)
            //{
            //    if (!Request.Files[upload].HasFile()) continue;
            //    string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
            //    string filename = Path.GetFileName(Request.Files[upload].FileName);
            //    Request.Files[upload].SaveAs(Path.Combine(path, filename));
            //}
            //return View();

            foreach (HttpPostedFileBase file in files)
            {
                string filePath = Path.Combine(TempPath, file.FileName);
                System.IO.File.WriteAllBytes(filePath, ReadData(file.InputStream));
            }

            return Json("All files have been successfully stored.");
        }

        private byte[] ReadData(Stream stream)
        {
            byte[] buffer = new byte[16 * 1024];

            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }

                return ms.ToArray();
            }
        }

        #endregion no-text coverage stuff
    }
}
